package main

import (
	"fmt"

	"github.com/esap/wechat"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
)

var app *wechat.Server

func init() {
	wechat.Debug = true
	cfg := &wechat.WxConfig{
		Token:          "wufly",
		AppId:          "wx2488810c3d62ef41",
		Secret:         "b05ad09f6f6bad3a08aa5424c7245e21",
		EncodingAESKey: "CGL9djYPx7cwTf6pjCX9tVgoJndbKm4TBaKmTruFxf9",
	}

	app = wechat.New(cfg)
}

func main() {
	s := g.Server()
	s.SetPort(1688)
	s.Domain("localhost").BindHandler("/login", login)
	s.Run()
	// Send("wufly")
}

func send(openID, text string) error {
	err := app.SendText(openID, text)
	if err != nil {
		return err.Error()
	}
	return nil
}

func getOpenID(jsCode string) (openID string) {
	userOauth, err := app.Jscode2Session(jsCode)
	if err != nil {
		fmt.Println(err.Error())
	}
	openID = userOauth.OpenId
	return
}

func login(r *ghttp.Request) {
	jsCode := r.GetString("code")
	glog.Info("js_code:", jsCode)
	// 获取openid
	openID := getOpenID(jsCode)
	glog.Info("openID:", openID)
	err := send(openID, "yyy")
	if err != nil {
		fmt.Println(err, "err")
	}
}
